/**
 * Created by hjqi on 2016/8/30.
 */
module.controller('ClusterListController',
    function ($scope, $rootScope, $uibModal, $state,$interval, $log, k8sService, $http, $cookies,clusterService) {

    // 服务模板
    var user = $cookies.get("username");
    $scope.username = user;
    $scope.animationsEnabled = true;

    $rootScope.curScope = $scope;

    var _deregister_udp_info = undefined;

    var promise = undefined;

    var loadData = function () {
        clusterService.getClustersInfo().then(function(result){
            $scope.clusters = result.data;

        }, function(err){
            alertify.alert('query applications err', err.data);
        });
    }
    $scope.init = function(){
        xenon_toggles_init();
    }

    $scope.$watchCollection('clusters', function (newvalue,oldvalue) {
        if(newvalue !== undefined)
            $scope.clusters = newvalue.slice();
    });

    $scope.currentPageServices = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 10;
    $scope.$watch("clusters + currentPage", function() {
        //var currentClusters = [];
        if ($scope.clusters) {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;
            var currentClusters = $scope.clusters.slice(begin, end);
            /*currentClusters.forEach(function(item) {
                //init
                item.nodeTotal =  item.nodes === undefined? 0: getTotalNodes(item.nodes).length;
                item.nodeAvailable = getAvailableNodes(item.nodes).length;

                if(item.nodeTotal !== 0 && item.nodeTotal === item.nodeAvailable ){
                    item.status = 'available';
                }else{
                    item.status = 'unavailable';
                }
            });
            $scope.currentPageServices = currentClusters;*/
            $scope.currentPageServices = currentClusters;
            getTotalInfo(currentClusters);
        }

    });

    loadData();

    $scope.createCluster = function () {
        //TODO create cluster

        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'template/cp/clusterModal.html',
            controller: 'ClusterCreateModController'
        });

        modalInstance.result.then(function (clusterItem) {
            //$scope.selected = selectedItem;
            clusterItem.status = 'not_ready';
            clusterItem.nodeAvailable = 0;
            clusterItem.nodeTotal = 0;
            $scope.clusters.push(clusterItem);
        }, function () {
            //$log.info('Modal dismissed at: ' + new Date());
        });
    }

    $scope.delete = function (data) {
        //TODO delete cluster
        alertify.confirm("Storage Operation","确定删除 "+data.name+" 集群?",
            function(){
                clusterService.deleteCluster(data.clusterId).then(function(ret){
                    if(ret.data === true){
                        var _idx = $scope.clusters.indexOf(data);
                        $scope.clusters.splice(_idx,1);
                        alertify.success("delete cluster success");
                    }
                }).catch(function(err){
                    alertify.alert('delete cluster error', 'delete cluster error :'+err);
                });
            },function(){

            }
        );

    };

    $scope.toggleAnimation = function () {
        $scope.animationsEnabled = !$scope.animationsEnabled;
    };

    $scope.$on('$destroy', function(){

        //unsubscribe event
        if(_deregister_udp_info !== undefined)
            _deregister_udp_info();
    });

    function getTotalNodes(nodes){
        var _ret = [];
        if(nodes !== undefined){
            for(var id in nodes){
                _ret.push(nodes[id]);
            }
        }

        return _ret;
    }

    function getNodeInfoMap(nodes){
        var _ret = {};
        if(nodes !== undefined){
            nodes.forEach(function(node){
                _ret[node.host] = node;
            });
        }

        return _ret;
    }

    function getAvailableNodes(nodes,nodeMap){
        var _ret = [];
        if(nodes !== undefined){
            nodes.forEach(function(node){
                if(nodeMap[node.metadata.name] !== undefined){
                    /*
                    if(node.status.conditions[1].type === 'Ready' && node.status.conditions[1].status === 'True'){
                        _ret.push(node);
                    }
                    */
                    var conds = node.status.conditions;
                    var _st = 'not_ready';
                    for(var i=0;i<conds.length;i++){
                        if(conds[i].type == 'Ready'){
                            if(conds[i].status == 'True')
                                _st = 'ready';
                            break;
                        }
                    }
                    if(_st === 'ready')
                        _ret.push(node);
                }
            });
        }

        return _ret;
    }

    function getTotalInfo(clusters){

        clusters.forEach(function(cluster){
            _reqNodeInfo(cluster);
        });
        function _reqNodeInfo(cluster){
            clusterService.getNodeInfo(cluster.clusterId).then(function(ret){
                if(ret.data.ret === true){

                    var _nodes = getTotalNodes(cluster.nodes);
                    var _nodeHostMap = getNodeInfoMap(_nodes);
                    cluster.nodeTotal = _nodes.length;
                    cluster.nodeAvailable = getAvailableNodes(ret.data.nodes,_nodeHostMap).length;

                    if(cluster.nodeTotal !== 0 && cluster.nodeTotal === cluster.nodeAvailable ){
                        cluster.status = 'available';
                    }else{
                        cluster.status = 'unavailable';
                    }
                }
            }).catch(function(err){

            });
        }
    }
});
